package com.example.jinzproduct.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.commons.entity.*;
import com.example.commons.utils.ApiEnumError;
import com.example.commons.utils.ApiResult;
import com.example.commons.vo.MyOrgRolesDeVo;
import com.example.commons.vo.OrgRolesListVo;
import com.example.jinzproduct.RedisUtil.RedisUtil;
import com.example.jinzproduct.server.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

import static com.example.commons.utils.TokenTag.TOKEN_TAG;


@Slf4j
@RestController
@RequestMapping("/jinZhiIndex/jzApi/organizion")
public class ApiOrganizionController   {

    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private UserService userService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private ExaminationPointService examinationPointService;
    @Autowired
    private UserRoleService userRoleService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * api查看机构详情
     *
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selExaminationDetails")
    @ApiOperation(value = "api小程序端-站点列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selExaminationDetails(String id) {

        List <MyOrgRolesDeVo> map= organizationRolesService.details(id);
        return ApiResult.success(map);
    }

    /**
     * 热搜机构
     * @Date: 2020-03-04
     */
    @GetMapping("/hotSearch")
    @ApiOperation(value = "api小程序端-站点列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> hotSearch( ) {


        return ApiResult.success(organizationRolesService.selecHotSearchOrg());
    }

    /**
     * api小程序端-站点列表数据接口
     *
     * @Description: 站点信息列表查询，参数：页码，显示数，站点名称（筛选条件），站点类型（筛选条件）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selExaminationPoint")
    @ApiOperation(value = "api小程序端-站点列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selExaminationPoint(String current, String number, String name, String type) {
        Map map = new HashMap();
        map.put("name",name);
        if(StringUtils.isNotBlank(type)){
            map.put("type",Integer.parseInt(type));
        }else{
            map.put("type","");
        }
        Page<OrgRolesListVo> page = organizationRolesService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            OrgRolesListVo obj = (OrgRolesListVo) page.getRecords().get(i);
            if (obj.getProfileId() != null){
                String[] profilesId = obj.getProfileId().split(",");
                String returnK = null;
                for(int j = 0;j<profilesId.length;j++){
                    if(!StringUtils.isBlank(profilesId[j])){
                        CertificateProfileDO certificateProfileDO = certificateProfileService.getById(Long.parseLong(profilesId[j]));
                        if (certificateProfileDO != null) {
                            if(returnK == null){
                                returnK = certificateProfileDO.getName();
                            }else{
                                returnK = returnK + "," + certificateProfileDO.getName();
                            }
                        }
                    }

                }
                obj.setProfileName(returnK);
            }
            list.add(obj);
        }
        page.setRecords(list);
        page.setTotal(organizationRolesService.selectListCount(Integer.parseInt(current), Integer.parseInt(number), map));
        return ApiResult.success(page);
    }



    /**
     * 考核站点申请
     * @param token
     * @param name
     * @param numberOfExaminees
     * @param enclosure
     * @param cachet
     * @param team
     * @param equipment
     * @param employer
     * @param state
     * @param province
     * @param profileName
     * @return
     */
    @PostMapping("/addExaminationPoint")
    @Transactional
    @RequiresAuthentication
    @ApiOperation(value = "web端-站点申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<Object> addExaminationPoint(@RequestHeader(value = TOKEN_TAG, required = false) String token,String name, Integer numberOfExaminees,
                                          String enclosure , String cachet, String team, String equipment, String employer ,Integer state, String province,String profileName) {//profileType 0:幼儿照护  1:产后恢复

        String userid=  redisUtil.get(token).toString();;
        //查询数据库根据用户id获取用户数据
        UserDO userDO = userService.getById(userid);
       // UserDO userDO = this.getClientUser(token);

        if (userDO==null){
            ApiResult.invalid();
        }
        UserDO user = userService.getByUserId(userDO.getId());
        QueryWrapper<CertificateProfileDO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",profileName);
        CertificateProfileDO certificateProfileDO=certificateProfileService.getOne(queryWrapper);
        int roleType=5;//幼儿照护考核站点
        if(profileName.equals("产后恢复职业技能等级证书")){
            roleType=6;//产后恢复考核站点
            if(!name.contains("-产后恢复"))
                name=name+"-产后恢复";
        }


        if (user.getOrgId() == null){
            QueryWrapper<OrganizationRolesDO> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("applicant_id" , user.getId());
            queryWrapper1.eq("profile_id",certificateProfileDO.getId());
            OrganizationRolesDO orgRole = organizationRolesService.getOne(queryWrapper1);
            if (orgRole != null) {
                //如果该机构不是考核站点则直接覆盖为考核站点申请，或是考核站点草稿状态则直接更新
                if ((orgRole.getRoleType()==5||orgRole.getRoleType()==6)&&(orgRole.getCheckerState() == 0 || orgRole.getCheckerState() == 1 || orgRole.getCheckerState() == 2)){
                    return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode(), ApiEnumError.STATION_POINT_INSERT.getMsg()+"1");
                }
                OrganizationNewsDO organizationNewsDO = organizationNewsService.getById(orgRole.getOrgId());
                organizationNewsDO.setName(name);//企业名称
                organizationNewsDO.setCreaterId(user.getId());//创建人id
                organizationNewsDO.setUpdaterId(user.getId());//更新人id
                organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
                organizationNewsDO.setCachet(cachet);
                organizationNewsDO.setNumberOfExaminees(numberOfExaminees);//考生数
                organizationNewsDO.setTeam(team);
                organizationNewsDO.setEquipment(equipment);
                organizationNewsDO.setEmployer(employer);
                organizationNewsDO.setProvince(province);
                boolean b = organizationNewsService.updateById(organizationNewsDO);
                if (!b) {
                    return ApiResult.fail("提交失败！错误代码：AOCaep101");
                }
                orgRole.setRoleType(roleType);
                orgRole.setApplicantId(user.getId());//申请人id
                orgRole.setApplicantDate(new Date());//申请时间
                orgRole.setEnclosure(enclosure);//机构申请附件
                orgRole.setCheckerState(state);

                boolean c = organizationRolesService.updateById(orgRole);
                if (c) {

                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep102");
                }

            }else {
                QueryWrapper<OrganizationNewsDO> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("name" , name);

                OrganizationNewsDO organizationNewsDO = organizationNewsService.getOne(queryWrapper2);
                if (organizationNewsDO != null){
                    QueryWrapper<OrganizationRolesDO> queryWrapper3=new QueryWrapper<>();
                    queryWrapper3.eq("name" , name);

                    OrganizationRolesDO rolesDO= organizationRolesService.getOne(queryWrapper3);

                  //  OrganizationRolesDO rolesDO= organizationRolesService.findOneByKv("org_id",organizationNewsDO.getId());
                 if(rolesDO!=null){
                     if(rolesDO.getCheckerState()!=4){
                         return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode() , "站点名称已经存在");
                     }
                 }

                }else {
                    organizationNewsDO = new OrganizationNewsDO();
                    organizationNewsDO.setName(name);//企业名称
                    organizationNewsDO.setCreaterId(user.getId());//创建人id
                    organizationNewsDO.setUpdaterId(user.getId());//更新人id
                    organizationNewsDO.setLeadingCadreId(user.getId());//负责人id
                    organizationNewsDO.setCachet(cachet);
                    organizationNewsDO.setNumberOfExaminees(numberOfExaminees);//考生数
                    organizationNewsDO.setTeam(team);
                    organizationNewsDO.setEquipment(equipment);
                    organizationNewsDO.setEmployer(employer);
                    organizationNewsDO.setProvince(province);
                    boolean b = organizationNewsService.save(organizationNewsDO);
                    if (!b) {
                        return ApiResult.fail("提交失败！错误代码：AOCaep103");
                    }
                }

                OrganizationRolesDO organizationRolesDO = new OrganizationRolesDO();
                organizationRolesDO.setRoleType(roleType);//机构角色
                organizationRolesDO.setOrgId(organizationNewsDO.getId());//机构id
                organizationRolesDO.setApplicantId(user.getId());//申请人id
                organizationRolesDO.setApplicantDate(new Date());//申请时间
                organizationRolesDO.setEnclosure(enclosure);//机构申请附件
                organizationRolesDO.setCheckerState(state);

                if(certificateProfileDO != null){
                    organizationRolesDO.setProfileId(certificateProfileDO.getId().toString());//默认幼儿照护证书
                }

                boolean c = organizationRolesService.save(organizationRolesDO);
                if (c) {
                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep104");
                }

            }

        }else {
            OrganizationNewsDO organizationNewsDO = organizationNewsService.getById(user.getOrgId());
            if(organizationNewsDO==null||!organizationNewsDO.getCreaterId().equals(user.getId())){
                return ApiResult.fail("提交失败！错误代码：AOCaep105");
            }
            QueryWrapper<OrganizationRolesDO> queryWrapper4=new QueryWrapper<>();
            queryWrapper4.eq("org_id",organizationNewsDO.getId());

            OrganizationRolesDO roles = organizationRolesService.getOne(queryWrapper4);
            if(roles!=null){
                if(roles.getRoleType()!=5&&roles.getRoleType()!=6){
                    OrganizationNewsDO organization = organizationNewsService.getById(roles.getOrgId());
                    organization.setName(name);//企业名称
                    organization.setCreaterId(user.getId());//创建人id
                    organization.setUpdaterId(user.getId());//更新人id
                    organization.setLeadingCadreId(user.getId());//负责人id
                    organization.setCachet(cachet);
                    organization.setNumberOfExaminees(numberOfExaminees);//考生数
                    organization.setTeam(team);
                    organization.setEquipment(equipment);
                    organization.setEmployer(employer);
                    organization.setProvince(province);
                    boolean b = organizationNewsService.updateById(organization);
                    if (!b) {
                        return ApiResult.fail("提交失败！错误代码：AOCaep107");
                    }

                    roles.setApplicantId(user.getId());//申请人id
                    roles.setRoleType(roleType);
                    roles.setApplicantDate(new Date());//申请时间
                    roles.setEnclosure(enclosure);//机构申请附件
                    roles.setCheckerState(state);

                    boolean c = organizationRolesService.updateById(roles);
                    if (c) {

                        user.setOrgId(organizationNewsDO.getId());
                        user.setOrgName(organizationNewsDO.getName());
                        return ApiResult.success();
                    } else {
                        return ApiResult.fail("提交失败！错误代码：AOCaep108");
                    }
                }
            }
            QueryWrapper<OrganizationRolesDO> queryWrapper5=new QueryWrapper<>();
            queryWrapper5.eq("applicant_id",user.getId());
            queryWrapper5.eq("role_type",roleType);
            OrganizationRolesDO rolesDO = organizationRolesService.getOne(queryWrapper5);

            if(rolesDO!=null){
                if(rolesDO.getCheckerState()==0||rolesDO.getCheckerState()==1||rolesDO.getCheckerState()==2)
                    return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode() , ApiEnumError.STATION_POINT_INSERT.getMsg()+"3");
                OrganizationNewsDO organization = organizationNewsService.getById(rolesDO.getOrgId());
                organization.setName(name);//企业名称
                organization.setCreaterId(user.getId());//创建人id
                organization.setUpdaterId(user.getId());//更新人id
                organization.setLeadingCadreId(user.getId());//负责人id
                organization.setCachet(cachet);
                organization.setNumberOfExaminees(numberOfExaminees);//考生数
                organization.setTeam(team);
                organization.setEquipment(equipment);
                organization.setEmployer(employer);
                organization.setProvince(province);
                boolean b = organizationNewsService.updateById(organization);
                if (!b) {
                    return ApiResult.fail("提交失败！错误代码：AOCaep107");
                }

                rolesDO.setApplicantId(user.getId());//申请人id

                rolesDO.setApplicantDate(new Date());//申请时间
                rolesDO.setEnclosure(enclosure);//机构申请附件
                rolesDO.setCheckerState(state);

                boolean c = organizationRolesService.updateById(rolesDO);
                if (c) {

                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep108");
                }
            }else{
                QueryWrapper<OrganizationNewsDO> queryWrapper6=new QueryWrapper<>();
                queryWrapper6.eq("name" , name);

                OrganizationNewsDO organization = organizationNewsService.getOne(queryWrapper6);
                if (organization != null){
                    return  ApiResult.build(ApiEnumError.STATION_POINT_INSERT.getCode() , ApiEnumError.STATION_POINT_INSERT.getMsg()+"4");
                }else {
                    organization = new OrganizationNewsDO();
                    organization.setName(name);//企业名称
                    organization.setCreaterId(user.getId());//创建人id
                    organization.setUpdaterId(user.getId());//更新人id
                    organization.setLeadingCadreId(user.getId());//负责人id
                    organization.setCachet(cachet);
                    organization.setNumberOfExaminees(numberOfExaminees);//考生数
                    organization.setTeam(team);
                    organization.setEquipment(equipment);
                    organization.setEmployer(employer);
                    organization.setProvince(province);
                    boolean b = organizationNewsService.save(organization);
                    if (!b) {
                        return ApiResult.fail("提交失败！错误代码：AOCaep109");
                    }
                }

                OrganizationRolesDO organizationRolesDO = new OrganizationRolesDO();
                organizationRolesDO.setRoleType(roleType);//机构角色
                organizationRolesDO.setOrgId(organizationNewsDO.getId());//机构id
                organizationRolesDO.setApplicantId(user.getId());//申请人id
                organizationRolesDO.setApplicantDate(new Date());//申请时间
                organizationRolesDO.setEnclosure(enclosure);//机构申请附件
                organizationRolesDO.setCheckerState(state);

                if(certificateProfileDO != null){
                    organizationRolesDO.setProfileId(certificateProfileDO.getId().toString());//默认幼儿照护证书
                }

                boolean c = organizationRolesService.save(organizationRolesDO);
                if (c) {

                    user.setOrgId(organizationNewsDO.getId());
                    user.setOrgName(organizationNewsDO.getName());
                    return ApiResult.success();
                } else {
                    return ApiResult.fail("提交失败！错误代码：AOCaep111");
                }
            }

        }
    }

    @PostMapping("/saveStation")
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<?> saveStation(@RequestHeader(value = TOKEN_TAG, required = false) String token,String name, Integer numberOfExaminees,
                             String enclosure , String cachet, String team, String equipment, String employer ,String orgId , Integer state, String province) {
        String userid=  redisUtil.get(token).toString();;
        //查询数据库根据用户id获取用户数据
        UserDO user = userService.getById(userid);

        if (user == null){
            return ApiResult.invalid();
        }
        OrganizationNewsDO orgNews = organizationNewsService.getById(orgId);
        orgNews.setName(name);//企业名称
        orgNews.setCreaterId(user.getId());//创建人id
        orgNews.setUpdaterId(user.getId());//更新人id
        orgNews.setLeadingCadreId(user.getId());//负责人id
        orgNews.setCachet(cachet);
        orgNews.setNumberOfExaminees(numberOfExaminees);//考生数
        orgNews.setTeam(team);
        orgNews.setEquipment(equipment);
        orgNews.setEmployer(employer);
        orgNews.setProvince(province);

        boolean c = organizationNewsService.updateById(orgNews);

        QueryWrapper<UserDO> queryWrapper6=new QueryWrapper<>();
        queryWrapper6.eq("orgId" , orgNews.getId());



        UserDO userDo = userService.getOne(queryWrapper6);
        if (userDo != null){

            List<Long> roleIds = userRoleService.listRoleId(userDo.getId());
            if (roleIds != null && roleIds.size() > 0) {
                userDo.setRoleIds(roleIds);
            } else {
                List<Long> list11 = new ArrayList<>();
                list11.add(56L);
                userDo.setRoleIds(list11);
            }

            userDo.setOrgName(name);
            userService.updateById(userDo);
        }

        QueryWrapper<ExaminationPointDO> queryWrapper7=new QueryWrapper<>();
        queryWrapper7.eq("org_id" , orgId);

        List<ExaminationPointDO> examPointList = examinationPointService.list(queryWrapper7);
        if (examPointList.size() != 0){
            for (ExaminationPointDO examinationPoint : examPointList){
                examinationPoint.setName(name);
            }
        }
        QueryWrapper<OrganizationRolesDO> queryWrapper8=new QueryWrapper<>();
        queryWrapper8.eq("role_type" , 5);
        queryWrapper8.eq( "org_id" , orgId);
        OrganizationRolesDO orgRole = organizationRolesService.getOne(queryWrapper8);
        orgRole.setCheckerState(state);
        orgRole.setEnclosure(enclosure);
        organizationRolesService.updateById(orgRole);

        if (c) {
            return ApiResult.success();
        } else {
            return ApiResult.fail("提交失败，错误代码：AOCss101");
        }
    }
}
